package cn.emailChat.ai.service.util;

/**
 * @Description 邮件主题归一化工具
 * @Author susu
 * @Date 2025/8/20
 */
public final class SubjectNormalizer {
    private SubjectNormalizer() {}

    public static String normalize(String subj) {
        if (subj == null) return "";
        String s = subj.trim();

        // 多语言 Re/Fwd 前缀多次剥离
        String prefix = "^(?i)(re|fw|fwd|回复|答复|回覆|转发|轉寄|res|sv|aw|antwort|ré|enc):\\s*";
        for (int i = 0; i < 5 && s.matches(prefix + ".*"); i++) {
            s = s.replaceFirst(prefix, "");
        }

        // 末尾常见票号 [ABC-123]
        s = s.replaceAll("\\s*\\[[A-Za-z]{2,10}-?\\d{2,8}]\\s*$", "");

        // 统一空白与常见标点；转小写
        s = s.replaceAll("\\s+", " ")
                .replaceAll("[\\p{Punct}&&[^-_/]]+", " ")
                .trim()
                .toLowerCase();
        return s;
    }

    // 简单相似度（编辑距离/比例），先给一个朴素实现；需要更强再替换
    public static boolean similarEnough(String a, String b) {
        if (a == null || b == null) return false;
        if (a.equals(b)) return true;
        int max = Math.max(a.length(), b.length());
        if (max == 0) return true;
        int dist = levenshtein(a, b);
        double sim = 1.0 - (dist * 1.0 / max);
        return sim >= 0.85;
    }

    private static int levenshtein(String s1, String s2) {
        int[] prev = new int[s2.length() + 1];
        int[] cur = new int[s2.length() + 1];
        for (int j = 0; j <= s2.length(); j++) prev[j] = j;
        for (int i = 1; i <= s1.length(); i++) {
            cur[0] = i;
            for (int j = 1; j <= s2.length(); j++) {
                int cost = s1.charAt(i - 1) == s2.charAt(j - 1) ? 0 : 1;
                cur[j] = Math.min(Math.min(cur[j - 1] + 1, prev[j] + 1), prev[j - 1] + cost);
            }
            int[] tmp = prev; prev = cur; cur = tmp;
        }
        return prev[s2.length()];
    }
}
